package com.tac.se2_project2;

import java.util.ArrayList;

import com.tac.se2_project2.MainActivity.CheckUserLoggedIn;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Button;
public class NewUser extends Activity{
	Intent intent;
	Button but;
	int contactID = 0;
	Spinner spinner;
	int cat_id = 0;
	DatabaseHandler db = new DatabaseHandler(this);
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    if(MainActivity.themes == "green")
			{
		    	setTheme(R.style.Green);
	        }
	        if(MainActivity.themes == "blue")
	        {
	        	setTheme(R.style.blue);
	        }

	        if(MainActivity.themes == "red")
	        {
	        	setTheme(R.style.red);
	        }
	    
        setContentView(R.layout.activity_user);
        
	    if(db.CheckUserLoggedIn()>0){
	    	((EditText)findViewById(R.id.loggedText)).setText("Logged In");
	    	((Button)findViewById(R.id.Upload)).setVisibility(View.VISIBLE);
	    	((Button)findViewById(R.id.Download)).setVisibility(View.VISIBLE);
	    	
	    }else{
	    	((EditText)findViewById(R.id.loggedText)).setText("Not Logged In");
	    	((Button)findViewById(R.id.Upload)).setVisibility(View.INVISIBLE);
	    	((Button)findViewById(R.id.Download)).setVisibility(View.INVISIBLE);
	    }

	}
	
	public void AddNewUser(View v) {
		EditText text = (EditText)findViewById(R.id.ErrorMessage);
		EditText usernameText = (EditText)findViewById(R.id.UsernameField);
		EditText passwordText = (EditText)findViewById(R.id.PasswordField);
		final String username = usernameText.getText().toString();
		
		//first call we need to check if the input username exists, if it doesn't then create the username
		boolean isDuplicate = new CloudHelper().CheckUsernameUnique(username);
		text.setText(isDuplicate == true ? "This username is already in use, please select another" : "");
		//finally create a user in the android database for this user.
		if(!isDuplicate){
			String salt = PasswordHasher.getSalt();
			String password = PasswordHasher.md5(passwordText.getText().toString() + salt);
			int userId = new CloudHelper().InsertNewUser(username, password, salt);
			DatabaseHandler db = new DatabaseHandler(this);
			//TODO: throw in seperate thread
			db.InsertNewCloudUser(userId, username);
			//we then need to upload all of this users current categories and contacts form the cloud and redirect to home page
			ArrayList<Contact> contacts = db.getAllContacts();
			Contact[] conts = new Contact[contacts.size()];
			for(int i = 0; i < contacts.size(); i ++){
				conts[i] = contacts.get(i);
			}
			new CloudHelper().UploadInformation(conts, db.retreiveAllCategories(), userId);
			((EditText)findViewById(R.id.loggedText)).setText("Logged In");
			new Handler().postDelayed(new Runnable() {
		        @Override
		        public void run() {
		        	Intent addIntent = new Intent(NewUser.this,MainActivity.class);
					addIntent.putExtra("StayOnPage",true);
					addIntent.putExtra("Username",username);
			    	startActivity(addIntent);
		        }
		    }, 1000);
			
		}
		else{
			
		}
		
	}
	
	public void LogIn(View v){
		EditText text = (EditText)findViewById(R.id.ErrorMessage);
		EditText usernameText = (EditText)findViewById(R.id.UsernameField);
		EditText passwordText = (EditText)findViewById(R.id.PasswordField);
		String username = usernameText.getText().toString();
		String password = passwordText.getText().toString();
		
		// First make a call to see if the username and password exists in teh database, if they do, pull
		// all of their contacts/categories and update this android devices tables
		int ValidLogin =  new CloudHelper().CheckUsernamePassword(username, password);
		if(ValidLogin > 0){
			DatabaseHandler db = new DatabaseHandler(this);
			text.setVisibility(View.INVISIBLE);
			//log user into android database
			ContactsCategories model = new CloudHelper().RetreiveInformation(ValidLogin);
			db.DeleteAllCategories();
			db.DeleteAllContacts();
			for(Category cat : model.categories){
				db.addCategory(cat);
			}
			for(Contact cont : model.contacts){
				db.addContact(cont);
			}
			//redirect to home page and log in 
			
			db.InsertNewCloudUser(ValidLogin, username);
			Intent addIntent = new Intent(NewUser.this,MainActivity.class);
			addIntent.putExtra("StayOnPage",true);
			((EditText)findViewById(R.id.loggedText)).setText("Logged In");
	    	startActivity(addIntent);
		}
		// Else display error message stating that username and password do not match
		else{
			text.setVisibility(View.VISIBLE);
			text.setText("Username and password do not match");
		}
		//
	}
	
	public void CancelNewUser(View v){
		Intent addIntent = new Intent(NewUser.this,MainActivity.class);
		addIntent.putExtra("StayOnPage",true);
    	startActivity(addIntent);
	}
	
	public void Upload(View v){
		EditText text = (EditText)findViewById(R.id.ErrorMessage);
		DatabaseHandler db = new DatabaseHandler(this);
		int userId = db.CheckUserLoggedIn();
		if(userId < 1){
			text.setText("Not Logged In!");
			return;
		}
		ArrayList<Contact> contacts = db.getAllContacts();
		Contact[] conts = new Contact[contacts.size()];
		for(int i = 0; i < contacts.size(); i ++){
			conts[i] = contacts.get(i);
		}
		Category[] cats = db.retreiveAllCategories();
		new CloudHelper().UploadInformation(conts, cats, userId);
		text.setVisibility(View.VISIBLE);
		text.setText("Upload Successful!");
	}
	
	public void Download(View V){
		EditText text = (EditText)findViewById(R.id.ErrorMessage);
		DatabaseHandler db = new DatabaseHandler(this);
		int userId = db.CheckUserLoggedIn();
		if(userId < 1){
			text.setText("Not Logged In!");
			return;
		}
		ContactsCategories model = new CloudHelper().RetreiveInformation(userId);
		ArrayList<Contact> contacts = db.getAllContacts();
		//this loop goes through all current android contacts and checks if there has been an update to them from the cloud
		int contactsCount = 0;
		for(Contact contact : contacts){
			for(Contact con : model.contacts){
				if(contact.getID() == con.getID()){
					if(contact.getModifyDate().getTime() < con.getModifyDate().getTime()){
						contacts.set(contactsCount, con);
					}
				}
			}
			contactsCount++;
		}
		
		//this loop goes through the cloud contacts and adds it to android if it is not already added
		for(Contact con : model.contacts){
			boolean found = false;
			for(Contact contact : contacts){
				if(con.getID() == contact.getID()){
					found = true;
				}
			}
			if(!found){
				contacts.add(con);
			}
		}
		//now remove current android contacts and add new ones
		db.DeleteAllCategories();
		db.DeleteAllContacts();
		for(Category cat : model.categories){
			db.addCategory(cat);
		}
		for(Contact contact : contacts){
			db.addContact(contact);
		}
		text.setText("Download Successful!");
	}
	
	public void onPause(){
		super.onPause();
	}
	

}
